<?php

namespace app\api\controller;

use think\App;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Env;

class Wechatqrcode
{

    //构造方法
    static $qrcode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?";
    static $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
    static $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?";

    //生成二维码
    public function getEwm($fqid = '1_231345', $type = 1)
    {
        try {
            $appid = Env::get('wx_chat.wx_appid_fwh');
            $secret = Env::get('wx_chat.wx_secret_fwh');
            $ACCESS_TOKEN = $this->getToken($appid, $secret);
            $url = $this->getQrcodeurl($ACCESS_TOKEN, $fqid, $type);
            //  save_log('测试保存的路径'.$url.'fid'.$fqid);
            $path = $this->DownLoadQr($url, time());
            //    echo $path;
            return ['code' => 1, 'path' => $path];
        } catch (\Throwable $th) {
            return ['code' => 0];
        }
    }

    protected function getQrcodeurl($ACCESS_TOKEN, $fqid, $type = 1)
    {
        $url = self::$qrcode_url . 'access_token=' . $ACCESS_TOKEN;
        if ($type == 1) {
            //生成永久二维码
            $qrcode = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": ' . '"' . $fqid . '"' . '}}}';
        } else {
            //生成临时二维码
            $qrcode = '{"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": ' . $fqid . '}}}';
        }
        //  echo $qrcode;
        $result = $this->http_post_data($url, $qrcode);
        $oo = json_decode($result[1]);
        //  var_dump($oo);
        if (empty($oo->ticket)) {
            return false;
        }
        if (!$oo->ticket) {
            $this->ErrorLogger('getQrcodeurl falied. Error Info: getQrcodeurl get failed');
            exit();
        }
        $url = self::$qrcode_get_url . 'ticket=' . $oo->ticket . '';
        return $url;
    }

    protected function getToken($appid, $secret)
    {
        $access_token = Cache::get('access_token');
        if (empty($access_token)) {
            $ACCESS_TOKEN = file_get_contents(self::$token_url . "appid=$appid&secret=$secret");
            $ACCESS_TOKEN = json_decode($ACCESS_TOKEN);
            $ACCESS_TOKEN = $ACCESS_TOKEN->access_token;
            Cache::set('access_token', $ACCESS_TOKEN, 3600);
            return $ACCESS_TOKEN;
        }
        return $access_token;
    }

    protected function http_post_data($url, $data_string)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        if (curl_errno($ch)) {
            $this->ErrorLogger('curl falied. Error Info: ' . curl_error($ch));
        }
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }

    //下载二维码到服务器
    protected function DownLoadQr($url, $filestring)
    {
        if ($url == "") {
            return false;
        }
        $filename = $filestring . rand(0, 99999999999) . '.jpg';
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $this->mkdirs('static/qrcode/');
        $fp2 = fopen('static/qrcode/' . $filename, "a");
        if (fwrite($fp2, $img) === false) {
            $this->ErrorLogger('dolwload image falied. Error Info: 无法写入图片');
            exit();
        }
        fclose($fp2);
        $hppt = is_https() ? 'https' : 'http';
        $url = $hppt . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . '/' . 'static/qrcode/' . $filename;
        return $url;
    }

    public function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }

        if (!$this->mkdirs(dirname($dir), $mode)) {
            return false;
        }

        return @mkdir($dir, $mode);
    }

    //错误日志
    private function ErrorLogger($errMsg)
    {
        file_put_contents('wx_qrcode.log', date('Y-m-d H:i:s') . ":" . $errMsg . PHP_EOL, FILE_APPEND);
    }

      /**
     * 模板通知消息
     *
     * @return void
     */
    public function send_notify_msg($openid, $data, $page = '')
    {
        $appid = Env::get('wx_chat.wx_appid_fwh');
        $secret = Env::get('wx_chat.wx_secret_fwh');
        $token = $this->getToken($appid, $secret); //$usera['access_token'];
        $posturl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $token;
        // $openid = $openid;
        $dt = array(
            "touser" => $openid."",
            'template_id' => Env::get('template.notify_template_id'),
            'url' => $page,
            'data' => $data
            //  array(
            //     'first' => array('value' => '新订单提醒'),
            //     'keyword1' => array('value' => '上门服务单'),
            //     'keyword2' => array('value' => '张三'),
            //     'keyword3' => array('value' => '13888888888'),
            //     'keyword4' => array('value' => '18888888888'),
            //     'keyword5' => array('value' => '鼓楼区省体育中心')
            // ),
        );
        $postjson = json_encode($dt);
        $resder = $this->http_curl($posturl, 'post', 'json', $postjson);
    }

    /**
     * 绑定模板消息
     *
     * @return void
     */
    public function send_bind_msg($openid, $data, $page = '/')
    {
        $appid = Env::get('wx_chat.wx_appid_fwh');
        $secret = Env::get('wx_chat.wx_secret_fwh');
        $token = $this->getToken($appid, $secret); //$usera['access_token'];
        $posturl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $token;
        // $openid = 'oM0TH0nyMtlyrP_J8cOL70oLYaCw';
        $dt = array(
            "touser" => $openid."",
            'template_id' => Env::get('template.bind_template_id'),
            'url' => $page,
            'data' => $data
            // array(
            //     'first' => array('value' => '微信绑定成功'),
            //     'keyword1' => array('value' => '张三'),
            //     'keyword2' => array('value' => '绑定微信成功')
            // ),
        );
        $postjson = json_encode($dt);
        $resder = $this->http_curl($posturl, 'post', 'json', $postjson);
        // file_put_contents('m.d', json_encode($resder));
        // var_dump($resder);
    }

    public function http_curl($url, $type, $res, $arr)
    {
        /*
        $url 请求的url
        $type 请求类型
        $res 返回数据类型
        $arr post请求参数
         */
        $ch = curl_init();
        /*$url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET';  */
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        if ($res == 'json') {
            return json_decode($output, true);
        }
    }

    public function cruise_left(){
        // $list = Db::name("goods_qrcode_user")->where("status",0)->select();
        // foreach($list as $k=>$v){
        //     if($v["failure_time"] <= time()){
        //         Db::name("goods_qrcode_user")->where("id",$v["id"])->update(["status"=>2]);
        //     }
        // }
        // return "okk";

        Db::name("goods_qrcode_user")->chunk(10,function($users){
            foreach($users as $user){
                if($user["failure_time"] <= time()){
                    Db::name("goods_qrcode_user")->where("id",$user["id"])->update(["status"=>2]);
                }
            }
        });
        return "okk";
    }
    

    
}
